from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
import pymysql
import pymysql.cursors

app = FastAPI()

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源，生产环境应限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 数据库配置
DB_CONFIG = {
    "host": "localhost",       # 数据库地址
    "user": "root",            # 数据库用户名
    "password": "0217",    # 数据库密码
    "database": "mydb",        # 数据库名
    "charset": "utf8mb4"
}

# 数据库连接函数
def get_db_connection():
    connection = pymysql.connect(**DB_CONFIG, cursorclass=pymysql.cursors.DictCursor)
    return connection

# 初始化数据库表
def init_database():
    try:
        conn = get_db_connection()
        with conn.cursor() as cursor:
            # 创建视频表
            cursor.execute('''
            CREATE TABLE IF NOT EXISTS videos (
                video_id VARCHAR(50) PRIMARY KEY,
                title VARCHAR(255) NOT NULL,
                description TEXT,
                category VARCHAR(100),
                author_id VARCHAR(50) NOT NULL,
                video_path VARCHAR(255) NOT NULL,
                publish_time VARCHAR(50) NOT NULL,
                duration FLOAT NOT NULL,
                remarks TEXT
            )
            ''')
        conn.commit()
        conn.close()
    except Exception as e:
        print(f"数据库初始化失败: {str(e)}")

# 初始化数据库
init_database()

@app.get("/")
def root():
    """根路径，返回服务状态和可用端点信息"""
    return {
        "status": "running",
        "service": "Video Information API",
        "version": "1.0.0",
        "endpoints": {
            "POST /video": "添加、修改或删除视频",
            "GET /video/{video_id}": "查询单个视频信息"
        }
    }

# 定义视频数据模型
class Video(BaseModel):
    video_id: str
    title: str
    description: Optional[str] = ""
    category: Optional[str] = ""
    author_id: str
    video_path: str
    publish_time: str
    duration: float
    remarks: Optional[str] = ""

class VideoRequest(BaseModel):
    op: str   # add / modify / delete
    video: Video

@app.post("/video")
def video_api(req: VideoRequest):
    """视频信息接口 - 支持添加、修改和删除操作"""
    vid = req.video.video_id

    # 验证操作类型
    if req.op not in ["add", "modify", "delete"]:
        return {"code": 400, "result": [], "msg": "非法操作类型"}

    conn = None
    try:
        conn = get_db_connection()
        with conn.cursor() as cursor:
            if req.op == "add":
                # 添加视频 - 先检查是否存在
                cursor.execute("SELECT COUNT(*) AS count FROM videos WHERE video_id = %s", (vid,))
                result = cursor.fetchone()
                if result['count'] > 0:
                    return {"code": 400, "result": [], "msg": "视频ID已存在"}
                
                # 插入新视频
                video_data = req.video.dict()
                cursor.execute('''
                INSERT INTO videos (video_id, title, description, category, author_id, 
                                  video_path, publish_time, duration, remarks)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
                ''', (video_data['video_id'], video_data['title'], video_data['description'],
                      video_data['category'], video_data['author_id'], video_data['video_path'],
                      video_data['publish_time'], video_data['duration'], video_data['remarks']))
                conn.commit()
                return {"code": 200, "result": [vid], "msg": "success"}

            elif req.op == "modify":
                # 修改视频 - 先检查是否存在
                cursor.execute("SELECT COUNT(*) AS count FROM videos WHERE video_id = %s", (vid,))
                result = cursor.fetchone()
                if result['count'] == 0:
                    return {"code": 404, "result": [], "msg": "视频ID不存在"}
                
                # 更新视频
                video_data = req.video.dict()
                cursor.execute('''
                UPDATE videos SET title = %s, description = %s, category = %s, 
                                 author_id = %s, video_path = %s, publish_time = %s, 
                                 duration = %s, remarks = %s
                WHERE video_id = %s
                ''', (video_data['title'], video_data['description'], video_data['category'],
                      video_data['author_id'], video_data['video_path'], video_data['publish_time'],
                      video_data['duration'], video_data['remarks'], vid))
                conn.commit()
                return {"code": 200, "result": [vid], "msg": "success"}

            elif req.op == "delete":
                # 删除视频 - 先检查是否存在
                cursor.execute("SELECT COUNT(*) AS count FROM videos WHERE video_id = %s", (vid,))
                result = cursor.fetchone()
                if result['count'] == 0:
                    return {"code": 404, "result": [], "msg": "视频ID不存在"}
                
                # 删除视频
                cursor.execute("DELETE FROM videos WHERE video_id = %s", (vid,))
                conn.commit()
                return {"code": 200, "result": [vid], "msg": "success"}
    except Exception as e:
        # 异常处理
        if conn:
            conn.rollback()
        return {"code": 500, "result": [], "msg": f"失败原因: {str(e)}"}
    finally:
        if conn:
            conn.close()

@app.get("/video/{video_id}")
def get_video(video_id: str):
    """查询单个视频信息"""
    conn = None
    try:
        conn = get_db_connection()
        with conn.cursor() as cursor:
            cursor.execute("SELECT * FROM videos WHERE video_id = %s", (video_id,))
            result = cursor.fetchone()
            if not result:
                return {"code": 404, "result": [], "msg": "视频ID不存在"}
            return {"code": 200, "result": result, "msg": "success"}
    except Exception as e:
        return {"code": 500, "result": [], "msg": f"失败原因: {str(e)}"}
    finally:
        if conn:
            conn.close()

# ✅ 一键运行服务器
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8001)  # 改为8002端口避免冲突
